package com.powernode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.AccessWhiteList;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @Description:
 * @Author: Tong Ziyu
 * @Date: 2024/10/8 10:30
 */

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AccessWhiteList accessWhiteList;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 执行过滤器逻辑
     * 1. 判断该次请求路径是否需要拦截
     * 2. 如果需要拦截 判断是否有权限
     * - 有权限,放行
     * - 没权限,拦截
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 拿到请求头,从中解析出请求路径
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getPath().toString();

        // 判断当前请求路径是否需要放行,路径是否存在于白名单中
        log.info("白名单路径:{}", accessWhiteList);
        if (accessWhiteList.getAllowUrls().contains(path)) {
            // 放行
            return chain.filter(exchange);
        }

        // 执行到这里时校验,请求路径不在白名单
        // 获取请求头中的token  token的格式: bearer token
        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);

        log.info("=============token值=============>:" + authorization);

        // 判断token
        if (StringUtils.hasText(authorization)) {
            // 进行校验
            String value = authorization.replace(AuthConstants.BEARER, "");
            // 判断value是否有值,并在查看是否在redis中存在,如果存在则放行
            // 约定好放进redis中key的格式为: login_token:
            if (StringUtils.hasText(value) && Boolean.TRUE.equals(stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + value))) {
                // 放行
                return chain.filter(exchange);
            }
        }
        // 走到这说明身份没有通过
        log.error("=============token校验失败,非法请求,请求路径:{},时间:{}=============>:", path, new Date());

        // 响应错误消息
        ServerHttpResponse response = exchange.getResponse();

        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);

        // 设置响应消息
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);

        ObjectMapper objectMapper = new ObjectMapper();

        byte[] bytes = null;
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);

        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
